package com.cade.agriculturemall.view.classify.goodsdetail;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseActivity;
import com.cade.agriculturemall.model.GoodsDetailEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.util.ToastUtils;
import com.cade.agriculturemall.utils.VerifyUtil;
import com.cade.agriculturemall.view.login.LoginActivity;
import com.cade.agriculturemall.view.shoppingCar.ShoppingCarFragment;
import com.cade.agriculturemall.view.shoppingCar.settlement.SettlementActivity;
import com.cade.agriculturemall.widget.GlideImageLoader;
import com.cade.agriculturemall.view.classify.goodsdetail.ServiceAssuranceDialog.ServiceAssuranceDialog;
import com.like.LikeButton;
import com.like.OnAnimationEndListener;
import com.like.OnLikeListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import static com.cade.agriculturemall.R.id.goods_detail_collect_btn;
import static com.cade.agriculturemall.R.id.goods_detail_like_btn;

/**
 * Created by Lobby on 2017/11/21.
 */

public class GoodsDetailActivity extends BaseActivity<GoodsDetailContract.IPresenter> implements GoodsDetailContract.IView, View.OnClickListener, OnLikeListener, OnAnimationEndListener {
    private Banner mBanner;
    private TextView mTvTitle;
    private TextView mTvSite;
    private TextView mTvPriceNew;
    private GoodsDetailEntity mEntity;
    private LikeButton mLikeBtn;
    private LikeButton mCollectLikeBtn;
    private TextView mSalesVolumeTv;
    private List<Integer> mSSList = new ArrayList<>();
    private String mTargetId;
    private ImageView img;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_goods_detail);
    }

    @Override
    public void setupView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setBackgroundResource(R.color.transparent);
        setupToolbar(true);
        mLikeBtn = (LikeButton) findViewById(R.id.goods_detail_like_btn);
        mLikeBtn.setOnAnimationEndListener(this);
        mLikeBtn.setOnLikeListener(this);
        mCollectLikeBtn = (LikeButton) findViewById(R.id.goods_detail_collect_btn);
        mCollectLikeBtn.setOnAnimationEndListener(this);
        mCollectLikeBtn.setOnLikeListener(this);
        mTargetId = this.getIntent().getStringExtra("objectId");
        mPresenter.getGoodsDetail(mTargetId);
        mBanner = (Banner) findViewById(R.id.goods_detail_img_banner);
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                ImageViewDialog dialog = new ImageViewDialog(GoodsDetailActivity.this, mEntity.getPicture(), position);
                dialog.show();
            }
        });
        mTvTitle = (TextView) findViewById(R.id.goods_detail_title);
        mTvSite = (TextView) findViewById(R.id.goods_detail_destinct);
        mTvPriceNew = (TextView) findViewById(R.id.goods_detail_tv_price_new);
        mSalesVolumeTv = (TextView) findViewById(R.id.goods_detail_tv_sales_volume);
        Button btnBuy = (Button) findViewById(R.id.goods_detail_btn_buy);
        btnBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!VerifyUtil.hadLogin()) {
                    showDialog();
                } else {
                    Intent intent = new Intent(getApplication(), SettlementActivity.class);
                    List<ShoppingCarsEntity> goodsSettlement = new ArrayList<>();
                    ShoppingCarsEntity shoppingCarsEntity = new ShoppingCarsEntity();
                    shoppingCarsEntity.setProId(mEntity);
                    shoppingCarsEntity.setShoper(mEntity.getShoper());
                    goodsSettlement.add(shoppingCarsEntity);
                    intent.putParcelableArrayListExtra("goodsSettlement", (ArrayList<? extends Parcelable>) goodsSettlement);
                    intent.putExtra("num", Float.parseFloat(mEntity.getPriceNew()));
                    intent.putExtra("type", "fromDetail");
                    startActivity(intent);
                }
            }
        });
        img= (ImageView) findViewById(R.id.goods_detail_img);
        ImageView imgA= (ImageView) findViewById(R.id.goods_detail_img_1);
        ImageView imgB= (ImageView) findViewById(R.id.goods_detail_img_2);
        ImageView imgC= (ImageView) findViewById(R.id.goods_detail_img_3);
        Glide.with(this).load(R.mipmap.goods_detail_first).into(img);
        Glide.with(this).load(R.mipmap.goods_detial_a).into(imgA);
        Glide.with(this).load(R.mipmap.goods_detial_b).into(imgB);
        Glide.with(this).load(R.mipmap.goods_detial_c).into(imgC);
        Button btnSave = (Button) findViewById(R.id.goods_detail_btn_save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(ShoppingCarFragment.instantiate()));
            }
        });
    }

    @Override
    public void setupEvent() {
        TextView textView = (TextView) findViewById(R.id.goods_detail_sever_tv);
        textView.setOnClickListener(this);
        TextView tvSpecification = (TextView) findViewById(R.id.goods_detail_tv_specification);
        tvSpecification.setOnClickListener(this);
    }

    @Override
    public void setupData() {

    }

    @Override
    public GoodsDetailContract.IPresenter setupPresenter() {
        return new GoodsDetailPresenter(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.goods_detail_sever_tv:
                ServiceAssuranceDialog dialog = new ServiceAssuranceDialog(this);
                dialog.getmAdapter().setSAList(mSSList);
                dialog.show();
                // 将对话框的大小按屏幕大小的百分比设置
                WindowManager windowManager = getWindowManager();
                Display display = windowManager.getDefaultDisplay();
                WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
                lp.width = (int) (display.getWidth() * 0.8); //设置宽度
                dialog.getWindow().setAttributes(lp);
                break;
            case R.id.goods_detail_tv_specification:
                SpecificationDialog specificationDialog = new SpecificationDialog(this,mEntity);
                specificationDialog.show();
                break;
        }
    }

    @Override
    public void setEntity(GoodsDetailEntity list) {
        mEntity = new GoodsDetailEntity();
        mEntity = list;
        if (mEntity != null) {
            if (VerifyUtil.hadLogin()) {
                mPresenter.isLike(mEntity, new GoodsDetailContract.ProductLikeListener() {
                    @Override
                    public void isProductLike(Boolean isLike) {
                        mLikeBtn.setLiked(isLike);
                    }
                });
                mPresenter.isInShoppingCars(mEntity, new GoodsDetailContract.ProductLikeListener() {
                    @Override
                    public void isProductLike(Boolean isLike) {
                        mCollectLikeBtn.setLiked(isLike);
                    }
                });
            }
            setBannerImage(mBanner, mEntity.getPicture());
            mPresenter.isinHistory(this, mTargetId);
            mTvTitle.setText(mEntity.getTitle());
            mTvTitle.setTextSize(12);
            mTvPriceNew.setText("优惠价 ￥" + mEntity.getPriceNew());
            String priceText = String.format("￥%1$s    原价：￥%2$s", mEntity.getPriceNew(), mEntity.getPriceOld());
            int z = priceText.lastIndexOf("原");
            SpannableStringBuilder style = new SpannableStringBuilder(priceText);
            style.setSpan(new AbsoluteSizeSpan(20), 0, 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            style.setSpan(new ForegroundColorSpan(Color.parseColor("#afafaf")), z, priceText.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            style.setSpan(new AbsoluteSizeSpan(19), z, priceText.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            mTvPriceNew.setText(style);
//            mTvPriceOld.setText("原价 ￥" + mEntity.getPriceOld());
            mTvSite.setText(mEntity.getSite());
            mSSList = mEntity.getTreatment();
            mSalesVolumeTv.setTextSize(12);
            mSalesVolumeTv.setText(mEntity.getSellOff() != null ? "销量：" + mEntity.getSellOff() : "销量：0");
        } else {
            ToastUtils.show("kong");
        }
    }

    public void setBannerImage(Banner banner, List<String> list) {
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(list);
        //设置mBanner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置标题集合（当mBanner样式有显示title时）
        banner.setBannerTitles(list);
        //设置自动轮播，默认为true
        banner.isAutoPlay(false);
        //设置轮播时间
        // mBanner.setDelayTime(1500);
        //设置指示器位置（当mBanner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //mBanner设置方法全部调用完毕时最后调用
        banner.start();

    }

    //      继承 mLikeButton.setOnLikeListener(this);
    @Override
    public void liked(LikeButton likeButton) {
        if (mTargetId != null) {
            switch (likeButton.getId()) {
                case R.id.goods_detail_like_btn:
                    if (!VerifyUtil.hadLogin()) {
                        showDialog();
                    } else {
                        mPresenter.addFavourite();
                    }
                    break;
                case R.id.goods_detail_collect_btn:
                    if (!VerifyUtil.hadLogin()) {
                        showDialog();
                    } else {
                        mPresenter.addCars();
                    }
                    break;
            }
        }
    }

    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.system_message).setMessage(R.string.have_no_login).
                setPositiveButton("登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                        intent.putExtra("goBack", true);
                        startActivity(intent);
                    }
                }).setNegativeButton("稍后去登陆", null);
    }

    @Override
    public void unLiked(LikeButton likeButton) {
        if (mTargetId != null) {
            switch (likeButton.getId()) {
                case goods_detail_like_btn:
                    mPresenter.deleteFavourite();
                    break;
                case goods_detail_collect_btn:
                    mPresenter.deleteShoppingCars();
                    break;
            }
        }
    }

    //   继承 OnAnimationEndListener( this);
    @Override
    public void onAnimationEnd(LikeButton likeButton) {

    }
}
